package com.maoning.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.maoning.common.constant.ProductConstant;
import com.maoning.product.entity.AttrAttrgroupRelationEntity;
import com.maoning.product.entity.AttrGroupEntity;
import com.maoning.product.entity.CategoryEntity;
import com.maoning.product.service.AttrAttrgroupRelationService;
import com.maoning.product.service.AttrGroupService;
import com.maoning.product.service.CategoryService;
import com.maoning.product.vo.AttrGroupRelationVo;
import com.maoning.product.vo.AttrRespVo;
import com.maoning.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.product.dao.AttrDao;
import com.maoning.product.entity.AttrEntity;
import com.maoning.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        final AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系
        final Integer attrType = attr.getAttrType();
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrType && attr.getAttrGroupId() != null){
            final AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            //这里有一个坑,需要注意存的时候一定用上一步save的那个对象,这里就是attrentity而不是attr,不然会导致没有attrid.
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        final String key = (String) params.get("key");
        final QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        if(catelogId != 0){
            queryWrapper.eq("catelog_id", catelogId);
        }
        final IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        final PageUtils pageUtils = new PageUtils(page);
        final List<AttrEntity> records = page.getRecords();
        final List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            final AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //设置分类和分组的名字
            if("base".equalsIgnoreCase(attrType)) {
                final AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if (relationEntity != null) {
                    final Long attrGroupId = relationEntity.getAttrGroupId();
                    if (attrGroupId != null) {
                        final AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
                        if (attrGroupEntity != null) {
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }

                    }
                }
            }
            final CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                final String categoryEntityName = categoryEntity.getName();
                if (StringUtils.isNotEmpty(categoryEntityName)) {
                    attrRespVo.setCatelogName(categoryEntityName);
                }
            }

            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(respVos);

        return pageUtils;
    }

    @Cacheable(value = "attr",key = "'attrinfo:' + #root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        final AttrEntity attrEntity = this.getById(attrId);
        final AttrRespVo respVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, respVo);
        final Integer attrType = attrEntity.getAttrType();
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrType){
            final AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if(relationEntity != null){
                final Long attrGroupId = relationEntity.getAttrGroupId();
                if(attrGroupId != null){
                    respVo.setAttrGroupId(attrGroupId);
                    final AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
                    if(attrGroupEntity != null){
                        respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
        }
        final Long catelogId = attrEntity.getCatelogId();
        if(catelogId != null){
            final Long[] catelogPath = categoryService.findCatelogPath(catelogId);
            respVo.setCatelogPath(catelogPath);
        }
        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attrVo) {
        final AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.updateById(attrEntity);

        final Integer attrType = attrVo.getAttrType();
        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() == attrType){
            final AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            relationEntity.setAttrId(attrVo.getAttrId());

            final int count = attrAttrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            if(count > 0){
                attrAttrgroupRelationService.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrVo.getAttrId()));
            }else {
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
    }

    /**
     * 根据分组id查找关联的所有属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        final List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        final List<Long> longList = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(CollectionUtils.isEmpty(entities)){
            return null;
        }
        final List<AttrEntity> listByIds = this.listByIds(longList);

        return listByIds;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        final List<AttrAttrgroupRelationEntity> relationEntities = Arrays.asList(vos).stream().map((item) -> {
            final AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(item.getAttrId());
            relationEntity.setAttrGroupId(item.getAttrGroupId());
            return relationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationService.deleteBatchRelation(relationEntities);
    }

    /**
     * 获取与属性分组id没有关联的属性id列表
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
//        1.当前分组只能关联自己所属的分类里面的所有属性
        final AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        final Long catelogId = attrGroupEntity.getCatelogId();
//        2.当前分组只能关联别的分组没有引用的属性
//        2.1找到当前分类下下的其他分组
        final List<AttrGroupEntity> group = attrGroupService.list(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        final List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
//        2.2这些组关联的属性
        final List<AttrAttrgroupRelationEntity> groupIds = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        final List<Long> attrIds = groupIds.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
//        2.3从当前分类的所有属性中移除这些属性
        final QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(!CollectionUtils.isEmpty(attrIds)){
            wrapper.notIn("attr_id", attrIds);
        }
        final String key = (String)params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        final IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        final PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    /**
     * 获取可以被检索的attrids
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        List<Long> list = baseMapper.selectSearchAttrs(attrIds);
        return list;
    }

}